const BASE_URL = 'http://121.37.1.66:8081';

export const api = {
  // 用户注册接口
  async sign_in_api(obj) {
    if (!obj.username || !obj.password || !obj.email || !obj.phone) {
      throw new Error('参数不完整');
    }
    
    try {
      const response = await new Promise((resolve, reject) => {
        uni.request({
          url: `${BASE_URL}/api/user/register`,
          method: 'POST',
          data: obj,
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        });
      });
      
      if (response.statusCode !== 200) {
        console.error('HTTP 错误:', response.statusCode);
        throw new Error('请求失败，状态码：' + response.statusCode);
      }
      
      if (response.data && response.data.code === 0) {
        return response.data;
      } else {
        const errorMsg = response.data?.msg || '注册失败';
        console.error('注册失败:', errorMsg);
        throw new Error(errorMsg);
      }
    } catch (error) {
      console.error('注册失败:', error);
      throw error;
    }
  },

  // 用户登录接口 - 重点修改部分
  async login_api(username, password) {
    if (!username || !password) {
      throw new Error('用户名和密码不能为空');
    }
  
    try {
      const response = await new Promise((resolve, reject) => {
        uni.request({
          url: `${BASE_URL}/api/user/login`,
          method: 'POST',
          data: { username, password },
          timeout: 10000,
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        });
      });
      
      console.log('登录API响应:', response); // 调试用
      
      // 修改判断逻辑，适应不同响应结构
      if (response.statusCode === 200) {
        // 情况1：直接返回token和数据
        if (response.data.token) {
          return response.data;
        }
        // 情况2：嵌套在data字段中
        else if (response.data.data && response.data.data.token) {
          return response.data.data;
        }
        // 情况3：code=0表示成功
        else if (response.data.code === 0) {
          return response.data;
        }
        // 其他情况视为失败
        else {
          const errorMsg = response.data?.msg || '登录失败';
          throw new Error(errorMsg);
        }
      } else {
        throw new Error(`请求失败，状态码：${response.statusCode}`);
      }
    } catch (err) {
      console.error('登录失败:', err);
      throw err;
    }
  },
  
  // 用户信息修改接口
  async user_update_api(userId, username, email, password, token) {
    if (!userId || !username || !email || !password) {
      throw new Error('参数不完整');
    }
 
    if (!token) {
      throw new Error('Authorization token不能为空');
    }
    
    try {
      const response = await new Promise((resolve, reject) => {
        uni.request({
          url: `${BASE_URL}/api/user/update`,
          method: 'PUT',
          header: {
            'Content-Type': 'application/json',
            'Authorization': token,
          },
          data: { 
            id: userId,
            username, 
            email, 
            password 
          },
          timeout: 10000,
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        });
      });
      
      if (response.statusCode === 200) {
        // 修改为适应code=0表示成功的API
        if (response.data.code === 0) {
          return response.data;
        } else {
          throw new Error(response.data.msg || '更新失败');
        }
      } else {
        throw new Error(`请求失败，状态码：${response.statusCode}`);
      }
    } catch (err) {
      console.error('用户信息修改失败:', err);
      const error = new Error(err.message || '用户信息修改失败');
      error.response = err.response;
      throw error;
    }
  },
  
  // 根据ID查询用户信息
  async getUserById(userId, token) {
    if (!userId || !token) {
      throw new Error('参数不完整');
    }
  
    try {
      const response = await new Promise((resolve, reject) => {
        uni.request({
          url: `${BASE_URL}/api/user/${userId}`,
          method: 'GET',
          header: {
            Authorization: token,
          },
          timeout: 10000,
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        });
      });
      
      console.log('获取用户信息响应:', response);
      
      if (response.statusCode === 200) {
        // 修改为适应code=0表示成功的API
        if (response.data.code === 0) {
          if (response.data.data) {
            return response.data.data; // 返回data字段中的用户数据
          } else {
            // 如果没有data字段，尝试直接返回响应数据
            return response.data;
          }
        } else {
          throw new Error(response.data.msg || '获取用户信息失败');
        }
      } else {
        throw new Error(response.data?.msg || `请求失败，状态码：${response.statusCode}`);
      }
    } catch (err) {
      console.error('获取用户信息失败:', err);
      throw new Error(err.message || '获取用户信息失败');
    }
  },
};